import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { message } from 'antd';
import InfoCard from '../components/InfoCard';
import { myAxios } from '../axios';
import { useStore } from '../stores/index';
import './Market.less';

const Market = () => {
  const navigate = useNavigate();
  const [currentPage, setCurrentPage] = useState(1);
  const [searchInput, setSearchInput] = useState('');
  const [helpData, setHelpData] = useState([]);
  const [loading, setLoading] = useState(true);
  const pageSize = 6;
  const userdata = useStore().userdata;
  const statusMap = {
    'pending': '进行中',
    'completed': '已完成'
  };

  const typeMap = {
    'offline': '线下',
    'online': '线上'
  };

  useEffect(() => {
    loadHelpList();
  }, []);

  const loadHelpList = async () => {
    try {
      setLoading(true);
      const res = await myAxios.get('/help/all/pending');
      if (res.data.code === 200) {
        const lowerCaseData = res.data.data.map(item => {
          const newItem = {};
          for (let key in item) {
            newItem[key.toLowerCase()] = item[key];
          }
          return newItem;
        });
        setHelpData(lowerCaseData);
      } else {
        message.error(res.data.message || '加载数据失败');
      }
    } catch (error) {
      console.error('加载数据失败:', error);
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleShowDetail = (data) => {
    navigate(`/home/detail/${data.help_id}`);
  };

  // 修改搜索函数，使用新的接口
  const handleSearch = async () => {
    if (!searchInput.trim()) {
      loadHelpList();
      return;
    }

    try {
      setLoading(true);
      const res = await myAxios.get(`/help/find/title?title=${encodeURIComponent(searchInput.trim())}`);
      
      if (res.data.code === 200) {
        const lowerCaseData = res.data.data.map(item => {
          const newItem = {};
          for (let key in item) {
            newItem[key.toLowerCase()] = item[key];
          }
          return newItem;
        });
        setHelpData(lowerCaseData);
        setCurrentPage(1); // 重置到第一页
      } else {
        message.error(res.data.message || '搜索失败');
      }
    } catch (error) {
      console.error('搜索失败:', error);
      message.error('搜索失败');
    } finally {
      setLoading(false);
    }
  };

  const handlePublish = () => {
    navigate('/home/upload');
  };

  const getCurrentPageData = () => {
    const start = (currentPage - 1) * pageSize;
    const end = start + pageSize;
    return helpData.slice(start, end);
  };

  return (
    <div className="market-container">
      <div className="market-header">
        <div className="search-container">
          {!userdata.isTeacher &&  (
            <button className="publish-btn" onClick={handlePublish}>
            发布
          </button>
          )}
          
          <div className="search-wrapper">
            <input 
              type="text" 
              className="search-input"
              placeholder="搜索公告标题"
              value={searchInput}
              onChange={(e) => setSearchInput(e.target.value)}
              onKeyPress={(e) => {
                if (e.key === 'Enter') {
                  handleSearch();
                }
              }}
            />
            <button className="search-btn" onClick={handleSearch}>
              搜索
            </button>
          </div>
        </div>
      </div>

      <div className="content-grid">
        {getCurrentPageData().map(item => (
          <InfoCard 
            key={item.help_id} 
            data={item} 
            statusMap={statusMap}
            typeMap={typeMap}
            onShowDetail={handleShowDetail}
          />
        ))}
      </div>

      {helpData.length > pageSize && (
        <div className="pagination">
          {Array.from({ length: Math.ceil(helpData.length / pageSize) }, (_, i) => i + 1).map(page => (
            <button
              key={page}
              className={`page-btn ${currentPage === page ? 'active' : ''}`}
              onClick={() => setCurrentPage(page)}
            >
              {page}
            </button>
          ))}
        </div>
      )}

      {helpData.length === 0 && !loading && (
        <div className="no-data">
          暂无数据
        </div>
      )}
    </div>
  );
};

export default Market;